import { action, computed, observable } from 'mobx';


export class Store {
    @observable status = false; //连接成功与否标志
    @observable step = 0; //0:未加入房间 1：加入房间 2：已准备 3：游戏开始
    @observable errorMsg = ""; //错误信息
    @observable essayList = [];
    @observable userName = "";
    @observable token = "";
    @observable socket;
    @observable room = {roomId:""};
    @observable message = []; //{type,类型（玩家发言，本人发言，系统通知）}

    @action
    connect = async () => {
        this.socket = new WebSocket('ws://192.168.0.107:8082/game');

        this.socket.onopen = () => {
            console.log("成功建立连接");
            this.errorMsg = "";
            this.status = true;
        }

        this.socket.onmessage = (event) => {
            let data = JSON.parse(event.data);
            console.log(data);
            this.errorMsg = data.msg === undefined?"":data.msg;
            if(data.type === "create"){
                if(data.code===200){
                    this.step = 1;
                    this.room.roomId = data.data.roomId;
                    console.log(this.room.roomId);
                }
                
            }
            else if(data.type === "system"){
                let msg = {
                    type:"system",
                    msg:data.message
                }
                this.message.push(msg);
            }
            else if(data.type === "theirs"){
                let msg = {
                    type:"theirs",
                    msg:data.message,
                    sender:data.sender
                }
                this.message.push(msg);
            }
            else if(data.type === "join"){
                if(data.code===200){
                    this.step = 1;
                }
            }
            
        }

        this.socket.onclose = () => {
            console.log('WebSocket连接已关闭!');
            this.errorMsg = "WebSocket连接已关闭!";
            this.status = false;
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket错误!', error);
            this.errorMsg = "WebSocket错误!";
            this.status = false;
        };
    }

    @action
    sendMessage = async (body) => {
        console.log(this.status);
        console.log(body);
        if(this.status){
            this.socket.send(body);
        }else{
            console.log("网络未连接");
            this.errorMsg = "网络未连接";
        }
        
    }

}